package com.apex.oauth.security.ice.filter;

import com.apex.oauth.security.ice.component.MyCustomUserLockNum;
import com.apex.oauth.security.ice.granted.Openid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Intellij IDE
 * User wangjian
 * Date 2017/11/9
 * Time 15:03
 * Version V1.01
 * 重新编写用户登录拦截
 */

public class UserLoginFilter extends AbstractAuthenticationProcessingFilter {

    private static final Logger log= LoggerFactory.getLogger(UserLoginFilter.class);

    @Autowired
    private MyCustomUserLockNum lockNum;

    private boolean postOnly = true;

    public UserLoginFilter() {
        super(new AntPathRequestMatcher("/login", "POST"));
    }

    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (postOnly &&! request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }
        String username = obtainUsername(request);
        String password = obtainPassword(request);
        String openid=request.getParameter("openid");
        String key= (String) request.getSession().getAttribute("IMAGE_SESSION_KEY");
        if (username == null) {
            username = "";
        }
        if (password == null) {
            password = "";
        }
        if(!StringUtils.isEmpty(username)){
            int num=lockNum.getUserLockMap(request,username);
            if(num>=5){
                log.error(username+":你已连续输错密码5次，请一小时后再试！");
                throw new BadCredentialsException("你已连续输错密码5次，请一小时后再试！");
            }
        }
        if(openid==null){
            openid="";
        }
        username = username.trim();
        List<GrantedAuthority> list=new ArrayList<>();
        list.add(new Openid(openid));
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                username, password,list);
        // Allow subclasses to set the "details" property
        this.setDetails(request, authRequest);

        return this.getAuthenticationManager().authenticate(authRequest);
    }

    protected String obtainPassword(HttpServletRequest request) {
        return request.getParameter("password");
    }

    protected String obtainUsername(HttpServletRequest request) {
        return request.getParameter("username");
    }

    public void setPostOnly(boolean postOnly) {
        this.postOnly = postOnly;
    }

    protected void setDetails(HttpServletRequest request,
                              UsernamePasswordAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }
}

